package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @author 王瑞
 * @description:
 * @date 2020/3/1  19:03
 */
public class StaticUtil {

    public static String getAbsolutePath(String path) {
        String path1 = StaticUtil.class.getResource("/").getPath();
        path1.replaceAll("\\\\", "/");
        return path1 + path;
    }

    public static void writeStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        //获取需要读写的文件字节流的总长度
        int allZise = 0;
        while (allZise == 0) {
            allZise = inputStream.available();
        }
        //已读字节数的累加变量
        int allRedyRead = 0;
        //每次固定读1024字节作缓冲
        int wileToRead = 1024;
        //需要读写的字节数组
        byte[] bytes = new byte[wileToRead];
        //先把请求头信息写进去
        outputStream.write(HttpProtocoUtil.getHttpHeader200(allZise).getBytes());
        //只要已经读的长度小于总长度 就一直读
        while (allRedyRead < allZise) {
            //到最后 如果已读长度加上固定长度大于总长度  就把剩下的长度赋值给固定长度 完成最后一次读取
            if ((allRedyRead + wileToRead) > allZise) {
                wileToRead = allZise - allRedyRead;
                bytes = new byte[wileToRead];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            allRedyRead += wileToRead;
        }

        outputStream.close();
        inputStream.close();

    }



}
